from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.filters import SearchFilter, OrderingFilter
from django_filters.rest_framework import DjangoFilterBackend
from drf_spectacular.utils import extend_schema_view, extend_schema, OpenApiParameter
from drf_spectacular.types import OpenApiTypes
from django.db import models
from django.utils import timezone

from apps.common.responses import (
    ApiResponseMixin, ConfigurableActionMixin,
    create_success_response_serializer,
    ValidationErrorResponseSerializer,
    NotFoundErrorResponseSerializer,
    ConflictErrorResponseSerializer
)

from .models import (
    AIProvider, AIModel, AIRole, AIConversation,
    AIMessage, TokenUsageLog, MessageTemplate, UserFavorite
)
from .serializers import (
    AIProviderSerializer, AIProviderCreateSerializer,
    AIModelSerializer, AIRoleSerializer, AIConversationSerializer,
    AIMessageSerializer, TokenUsageLogSerializer,
    MessageTemplateSerializer, UserFavoriteSerializer,
    AIProviderTestSerializer, ConversationCreateSerializer,
    MessageSendSerializer, BatchOperationSerializer,
    TokenUsageStatsSerializer, ConversationExportSerializer
)
from .ai_service import AIService


@extend_schema_view(
    list=extend_schema(
        summary="获取AI提供商列表",
        description="获取用户的AI提供商列表，支持分页、搜索和过滤",
        parameters=[
            OpenApiParameter(name='provider_type', type=OpenApiTypes.STR, description='提供商类型过滤'),
            OpenApiParameter(name='is_active', type=OpenApiTypes.BOOL, description='是否启用过滤'),
        ],
    ),
    retrieve=extend_schema(
        summary="获取AI提供商详情",
        responses={
            200: create_success_response_serializer(AIProviderSerializer, "获取成功", "Retrieve"),
            404: NotFoundErrorResponseSerializer,
        }
    ),
    create=extend_schema(
        summary="创建AI提供商",
        request=AIProviderCreateSerializer,
        responses={
            201: create_success_response_serializer(AIProviderSerializer, "创建成功", "Create"),
            400: ValidationErrorResponseSerializer,
        }
    ),
    update=extend_schema(
        summary="更新AI提供商",
        request=AIProviderCreateSerializer,
        responses={
            200: create_success_response_serializer(AIProviderSerializer, "更新成功", "Update"),
            400: ValidationErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    ),
    destroy=extend_schema(
        summary="删除AI提供商",
        responses={
            204: None,
            404: NotFoundErrorResponseSerializer,
        }
    ),
)
class AIProviderViewSet(ConfigurableActionMixin, ApiResponseMixin, viewsets.ModelViewSet):
    """AI提供商管理ViewSet"""
    serializer_class = AIProviderSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_fields = ['provider_type', 'is_active', 'is_public']
    search_fields = ['name']
    ordering_fields = ['created_at', 'updated_at', 'name']
    ordering = ['-created_at']
    
    def get_queryset(self):
        """获取当前用户的提供商"""
        user = self.request.user
        if user.is_staff:
            return AIProvider.objects.all()
        return AIProvider.objects.filter(
            models.Q(owner=user) | models.Q(is_public=True)
        )
    
    def get_serializer_class(self):
        """根据操作类型选择序列化器"""
        if self.action in ['create', 'update', 'partial_update']:
            return AIProviderCreateSerializer
        return AIProviderSerializer
    
    def perform_create(self, serializer):
        """创建时设置所有者"""
        serializer.save(
            owner=self.request.user,
            created_by=self.request.user
        )
    
    def perform_update(self, serializer):
        """更新时设置更新者"""
        serializer.save(updated_by=self.request.user)
    
    @extend_schema(
        summary="测试AI提供商连接",
        request=AIProviderTestSerializer,
        responses={
            200: create_success_response_serializer(
                AIProviderTestSerializer, 
                "测试成功", 
                "Test"
            ),
            400: ValidationErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    )
    @action(detail=True, methods=['post'])
    def test_connection(self, request, pk=None):
        """测试AI提供商连接"""
        provider = self.get_object()
        serializer = AIProviderTestSerializer(data=request.data)
        
        if not serializer.is_valid():
            return self.error_response("测试参数无效", errors=serializer.errors, code=400)
        
        # 检查权限
        if not provider.can_edit(request.user):
            return self.error_response("无权限测试此提供商", code=403)
        
        try:
            # 使用AI提供商测试服务进行实际连接测试
            from .services import AIProviderTestService

            test_message = serializer.validated_data['test_message']
            test_service = AIProviderTestService(provider)
            result = test_service.test_connection(test_message)

            if result['status'] == 'success':
                return self.success_response(result, result['message'])
            else:
                return self.error_response(result['message'], data=result, code=400)
            
        except Exception as e:
            return self.error_response(f"连接测试失败: {str(e)}", code=500)


@extend_schema_view(
    list=extend_schema(
        summary="获取AI模型列表",
        description="获取可用的AI模型列表，支持分页、搜索和过滤",
        parameters=[
            OpenApiParameter(name='provider', type=OpenApiTypes.INT, description='提供商ID过滤'),
            OpenApiParameter(name='is_active', type=OpenApiTypes.BOOL, description='是否启用过滤'),
        ],
    ),
    retrieve=extend_schema(
        summary="获取AI模型详情",
        responses={
            200: create_success_response_serializer(AIModelSerializer, "获取成功", "Retrieve"),
            404: NotFoundErrorResponseSerializer,
        }
    ),
    create=extend_schema(
        summary="创建AI模型",
        responses={
            201: create_success_response_serializer(AIModelSerializer, "创建成功", "Create"),
            400: ValidationErrorResponseSerializer,
        }
    ),
    update=extend_schema(
        summary="更新AI模型",
        responses={
            200: create_success_response_serializer(AIModelSerializer, "更新成功", "Update"),
            400: ValidationErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    ),
    destroy=extend_schema(
        summary="删除AI模型",
        responses={
            204: None,
            404: NotFoundErrorResponseSerializer,
        }
    ),
)
class AIModelViewSet(ConfigurableActionMixin, ApiResponseMixin, viewsets.ModelViewSet):
    """AI模型管理ViewSet"""
    serializer_class = AIModelSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_fields = ['provider', 'is_active']
    search_fields = ['name', 'model_code']
    ordering_fields = ['created_at', 'updated_at', 'name']
    ordering = ['-created_at']
    
    def get_queryset(self):
        """获取用户可访问的模型"""
        user = self.request.user
        if user.is_staff:
            return AIModel.objects.all()
        
        # 用户可以访问自己的提供商的模型和公开提供商的模型
        return AIModel.objects.filter(
            models.Q(provider__owner=user) | 
            models.Q(provider__is_public=True)
        ).filter(is_active=True)
    
    def perform_create(self, serializer):
        """创建时设置创建者"""
        serializer.save(created_by=self.request.user)
    
    def perform_update(self, serializer):
        """更新时设置更新者"""
        serializer.save(updated_by=self.request.user)


@extend_schema_view(
    list=extend_schema(
        summary="获取AI角色列表",
        description="获取用户的AI角色列表，支持分页、搜索和过滤",
        parameters=[
            OpenApiParameter(name='category', type=OpenApiTypes.STR, description='角色分类过滤'),
            OpenApiParameter(name='is_public', type=OpenApiTypes.BOOL, description='是否公开过滤'),
        ],
    ),
    retrieve=extend_schema(
        summary="获取AI角色详情",
        responses={
            200: create_success_response_serializer(AIRoleSerializer, "获取成功", "Retrieve"),
            404: NotFoundErrorResponseSerializer,
        }
    ),
    create=extend_schema(
        summary="创建AI角色",
        responses={
            201: create_success_response_serializer(AIRoleSerializer, "创建成功", "Create"),
            400: ValidationErrorResponseSerializer,
        }
    ),
    update=extend_schema(
        summary="更新AI角色",
        responses={
            200: create_success_response_serializer(AIRoleSerializer, "更新成功", "Update"),
            400: ValidationErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    ),
    destroy=extend_schema(
        summary="删除AI角色",
        responses={
            204: None,
            404: NotFoundErrorResponseSerializer,
        }
    ),
)
class AIRoleViewSet(ConfigurableActionMixin, ApiResponseMixin, viewsets.ModelViewSet):
    """AI角色管理ViewSet"""
    serializer_class = AIRoleSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_fields = ['category', 'is_public']
    search_fields = ['name', 'system_prompt']
    ordering_fields = ['created_at', 'updated_at', 'usage_count', 'name']
    ordering = ['-usage_count', '-created_at']

    def get_queryset(self):
        """获取用户可访问的角色"""
        user = self.request.user
        if user.is_staff:
            return AIRole.objects.all()

        # 用户可以访问自己创建的角色和公开角色
        return AIRole.objects.filter(
            models.Q(created_by=user) | models.Q(is_public=True)
        )

    def perform_create(self, serializer):
        """创建时设置创建者"""
        serializer.save(created_by=self.request.user)

    def perform_update(self, serializer):
        """更新时设置更新者"""
        serializer.save(updated_by=self.request.user)


@extend_schema_view(
    list=extend_schema(
        summary="获取AI对话会话列表",
        description="获取用户的AI对话会话列表，支持分页、搜索和过滤",
        parameters=[
            OpenApiParameter(name='status', type=OpenApiTypes.STR, description='会话状态过滤'),
            OpenApiParameter(name='ai_model', type=OpenApiTypes.INT, description='AI模型ID过滤'),
            OpenApiParameter(name='ai_role', type=OpenApiTypes.INT, description='AI角色ID过滤'),
        ],
    ),
    retrieve=extend_schema(
        summary="获取AI对话会话详情",
        responses={
            200: create_success_response_serializer(AIConversationSerializer, "获取成功", "Retrieve"),
            404: NotFoundErrorResponseSerializer,
        }
    ),
    create=extend_schema(
        summary="创建AI对话会话",
        responses={
            201: create_success_response_serializer(AIConversationSerializer, "创建成功", "Create"),
            400: ValidationErrorResponseSerializer,
        }
    ),
    update=extend_schema(
        summary="更新AI对话会话",
        responses={
            200: create_success_response_serializer(AIConversationSerializer, "更新成功", "Update"),
            400: ValidationErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    ),
    destroy=extend_schema(
        summary="删除AI对话会话",
        responses={
            204: None,
            404: NotFoundErrorResponseSerializer,
        }
    ),
)
class AIConversationViewSet(ConfigurableActionMixin, ApiResponseMixin, viewsets.ModelViewSet):
    """AI对话会话管理ViewSet"""
    serializer_class = AIConversationSerializer
    filter_backends = [DjangoFilterBackend, SearchFilter, OrderingFilter]
    filterset_fields = ['status', 'ai_model', 'ai_role']
    search_fields = ['title']
    ordering_fields = ['created_at', 'updated_at', 'last_message_at', 'used_tokens']
    ordering = ['-last_message_at', '-created_at']

    def get_queryset(self):
        """获取用户的对话会话"""
        user = self.request.user
        if user.is_staff:
            return AIConversation.objects.all()
        return AIConversation.objects.filter(owner=user)

    def perform_create(self, serializer):
        """创建时设置所有者"""
        serializer.save(
            owner=self.request.user,
            created_by=self.request.user
        )

    def perform_update(self, serializer):
        """更新时设置更新者"""
        serializer.save(updated_by=self.request.user)

    @extend_schema(
        summary="发送消息",
        request=MessageSendSerializer,
        responses={
            200: create_success_response_serializer(
                MessageSendSerializer,
                "消息发送成功",
                "SendMessage"
            ),
            400: ValidationErrorResponseSerializer,
            404: NotFoundErrorResponseSerializer,
        }
    )
    @action(detail=True, methods=['post'])
    def send_message(self, request, pk=None):
        """发送消息到AI对话"""
        conversation = self.get_object()
        serializer = MessageSendSerializer(data=request.data)

        if not serializer.is_valid():
            return self.error_response("消息参数无效", errors=serializer.errors, code=400)

        # 检查权限
        if not conversation.can_edit(request.user):
            return self.error_response("无权限操作此会话", code=403)

        try:
            # 使用AI服务发送消息
            ai_service = AIService(conversation)
            result = ai_service.send_message(
                content=serializer.validated_data['content'],
                user=request.user,
                include_context=serializer.validated_data.get('include_context', True),
                context_limit=serializer.validated_data.get('context_limit', 10),
                max_context_tokens=serializer.validated_data.get('max_context_tokens', 120000),
                parent_message_id=serializer.validated_data.get('parent_message_id')
            )

            return self.success_response(result, "消息发送成功")

        except Exception as e:
            return self.error_response(f"消息发送失败: {str(e)}", code=500)
